package cn.tedu.csmall.passport.controller;

import cn.tedu.csmall.passport.pojo.param.AdminAddNewParam;
import cn.tedu.csmall.passport.pojo.param.AdminLoginInfoParam;
import cn.tedu.csmall.passport.pojo.param.AdminUpdateInfoParam;
import cn.tedu.csmall.passport.security.LoginPrincipal;
import cn.tedu.csmall.passport.service.AdminService;
import cn.tedu.csmall.passport.web.JsonResult;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@RestController
@RequestMapping("/admin/")
@Api(tags = "01.管理员管理模块")
@Slf4j
@Validated
public class AdminController {

    private final AdminService adminService;
    public final static String HEADER_AUTHORIZATION = "Authorization";

    @Autowired// 可以通过构造方法上加注解来自动注入（最安全的），但不适用于自动装配的属性的数量可能随着需求而增减的情况
    public AdminController(AdminService adminService) {
        this.adminService = adminService;
    }

    @PostMapping("login")
    @ApiOperation("管理员的登录")
    @ApiOperationSupport(order = 50)
    public JsonResult login(AdminLoginInfoParam adminLoginInfoParam, @ApiIgnore HttpServletRequest request) {
        log.debug("开始处理【管理员登录】的请求，参数：{}", adminLoginInfoParam);
        String remoteAddr = request.getRemoteAddr();
        String userAgent = request.getHeader(adminService.HEADER_USER_AGENT);
        return JsonResult.success(adminService.login(adminLoginInfoParam, remoteAddr, userAgent));
    }

    @PostMapping("logout")
    @ApiOperation("管理员的退出登录")
    @ApiOperationSupport(order = 60)
    public JsonResult logout(@RequestHeader(HEADER_AUTHORIZATION) String jwt) {
        log.debug("开始处理【管理员退出登录】的请求，参数：{}", jwt);
        adminService.logout(jwt);
        return JsonResult.success();
    }

    // http://localhost:8080/album/add-new?name=TestName001&description=TestDescription&sort=99
    // @RequestMapping(value = "add-new",method = RequestMethod.POST)
    @PostMapping("add-new")
    @PreAuthorize("hasAuthority('/ams/admin/add-new')")
    @ApiOperation("添加管理员")
    @ApiOperationSupport(order = 100)
    public JsonResult addNew(@Valid AdminAddNewParam adminAddNewParam) {
        log.debug("开始处理【添加管理员请求，参数：{}】",adminAddNewParam);
        adminService.addNew(adminAddNewParam);
        return JsonResult.success();
    }

    @GetMapping("list")
    @ApiOperation("分页查询管理员列表")
    @ApiImplicitParam(name = "pageNum", value = "页码", required = true, dataType = "int")
    public JsonResult list(@RequestParam @Range(min = 1, message = "请提供正确的页码值！") Integer pageNum) {
        return JsonResult.success(adminService.list(pageNum));
    }

    @PostMapping("/{adminId:[0-9]+]}/delete")
    @PreAuthorize("hasAuthority('/ams/admin/delete')")
    @ApiOperation("根据ID删除管理员")
    @ApiImplicitParam(name = "adminId", value = "管理员ID", required = true, dataType = "long")
    public JsonResult delete(@Range(min = 1, message = "ID值不合法！") @PathVariable("adminId") Long id) {
        adminService.deleteById(id);
        return JsonResult.success();
    }

    @PostMapping("updateInfoById")
    @PreAuthorize("hasAuthority('/ams/admin/update')")
    @ApiOperation("修改管理员信息")
    public JsonResult updateInfoById(@RequestParam @Range(min = 1, message = "请提交有效的管理员ID") Long id,
                                     @Valid AdminUpdateInfoParam adminUpdateInfoParam) {
        adminService.updateInfoById(id, adminUpdateInfoParam);
        return JsonResult.success();
    }

    @GetMapping("getStandardById")
    @ApiOperation("根据id查询管理员信息")
    public JsonResult getStandardById(@RequestParam @Range(min = 1, message = "根据ID查询管理员信息失败,请提交正确的管理员ID") Long id) {

        return JsonResult.success(adminService.getStandardById(id));

    }

    @PostMapping("principal")
    @ApiOperation("获取当事人")
    public JsonResult getPrincipal(@ApiIgnore @AuthenticationPrincipal LoginPrincipal loginPrincipal) {// @AuthenticationPrincipal注解可以获取已经登录的当事人信息
        log.debug("当事人ID：{}", loginPrincipal.getId());
        log.debug("当事人用户名：{}", loginPrincipal.getUsername());
        return JsonResult.success("功能还未开发！");
    }

    @PostMapping("updatePwdById")
    @PreAuthorize("hasAuthority('/ams/admin/update')")
    @ApiOperation("根据ID修改密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "管理员ID", required = true, dataType = "long"),
            @ApiImplicitParam(name = "pwd", value = "管理员密码", required = true, dataType = "String"),
    })
    public JsonResult updatePwdById(Long id, String pwd) {
        log.debug("开始处理【修改管理员密码】，修改的管理员ID为：{}", id);
        adminService.updatePwdById(id, pwd);
        return JsonResult.success();
    }

    @PostMapping("setEnable")
    @PreAuthorize("hasAuthority('/ams/admin/update')")
    @ApiOperation("设置启用或者禁用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "管理员ID", required = true, dataType = "long"),
            @ApiImplicitParam(name = "enable", value = "是否启用", required = true, dataType = "int"),
    })
    public JsonResult setEnableOrDisable(Long id, Integer enable) {
        log.debug("开始处理【设置启用或者禁用】，修改的管理员ID为：{}，启用状态为：{}", id, enable);
        adminService.setEnable(id, enable);
        return JsonResult.success();
    }

}
